package com.meritdata.cloud.data.service.development.service;

import com.meritdata.cloud.data.base.Page;
import com.meritdata.cloud.data.service.development.model.DataApi;
import com.meritdata.cloud.data.service.development.model.QDataApi;
import com.meritdata.cloud.data.service.development.repository.IDataApiDao;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class DataApiService  {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private IDataApiDao iDataApiDao;

    public Page<DataApi> page(Map<String,Object> param) {
        Page p = new Page();
        QDataApi qDataApi = QDataApi.dataApi;
        Integer pageNum = Integer.parseInt((String) param.get("page"));
        Integer sizeNum = Integer.parseInt((String) param.get("rows"));
        p.setPageNum(pageNum);
        p.setPageSize(sizeNum);
        Pageable pageable = PageRequest.of(pageNum-1,sizeNum);
        Predicate predicate =qDataApi.categoryId.eq((String) param.get("categoryId"));
        if(StringUtils.isNotBlank((String)param.get("name"))){
            ExpressionUtils.and(predicate,qDataApi.name.like((String)param.get("name")));
        }
        List<DataApi> ls =jpaQueryFactory.selectFrom(qDataApi)
                .where(predicate)
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .orderBy(qDataApi.updateTime.desc())
                .fetch();
        Long count = jpaQueryFactory.selectFrom(qDataApi)
                .where(predicate)
                .fetchCount();
        p.setTotalCount(count);
        p.setDatas(ls);
        return p;
    }

    public DataApi save(DataApi d) {
        return iDataApiDao.save(d);
    }

    public Optional<DataApi> findById(String id) {
        return iDataApiDao.findById(Long.valueOf(id));
    }

    public Optional<DataApi> update(String id, String name, String type, String url, String description, Date updateTime) {
        iDataApiDao.update(Long.valueOf(id),name,url,description,type,updateTime);
        return iDataApiDao.findById(Long.valueOf(id));
    }
}
